<template>
  <el-dialog v-model="dialogInfo.visible" :title="dialogInfo.title" :width="dialogInfo.width" align-center>
    <el-form ref="formRef" label-position="left" :model="formModel" :rules="formRules" label-width="120px">
      <el-row>
        <el-col :sm="24">
          <el-form-item label="角色ID" prop="Id">
            <el-input v-model.trim="formModel.Id" autocomplete="off" disabled></el-input>
          </el-form-item>
        </el-col>
        <el-col :sm="24">
          <el-form-item label="用户名" prop="UserName">
            <el-input v-model.trim="formModel.UserName" autocomplete="off" placeholder="请输入用户名"></el-input>
          </el-form-item>
        </el-col>
        <el-col :sm="24">
          <el-form-item label="姓名" prop="RealName">
            <el-input v-model.trim="formModel.RealName" autocomplete="off" placeholder="请输入姓名"></el-input>
          </el-form-item>
        </el-col>
        <el-col :sm="24">
          <el-form-item label="手机号" prop="Mobile">
            <el-input v-model.trim="formModel.Mobile" autocomplete="off" placeholder="请输入手机号"></el-input>
          </el-form-item>
        </el-col>
        <el-col :sm="24">
          <el-form-item label="邮箱" prop="Email">
            <el-input v-model.trim="formModel.Email" autocomplete="off" placeholder="请输入邮箱"></el-input>
          </el-form-item>
        </el-col>
        <el-col :sm="24">
          <el-form-item label="密码" prop="UserPwd">
            <el-input v-model.trim="formModel.UserPwd" autocomplete="off" placeholder="留空则不修改"></el-input>
          </el-form-item>
        </el-col>
        <el-col :sm="24">
          <el-form-item label="角色" prop="RoleIds">
            <el-select class="w100" v-model.trim="formModel.RoleIds" multiple placeholder="请选择">
              <el-option v-for="item in optionsOfRoles" :key="item.Id" :label="item.Name" :value="item.Id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :sm="24">
          <el-form-item label="超级管理员" prop="IsSuper">
            <el-switch size="large" v-model="formModel.IsSuper" inline-prompt active-value="1" inactive-value="0" active-text="是" inactive-text="否" />
          </el-form-item>
        </el-col>
        <el-col :sm="24">
          <el-form-item label="状态" prop="Status">
            <el-switch size="large" v-model="formModel.Status" inline-prompt active-value="1" inactive-value="0" active-text="启用" inactive-text="禁用" />
          </el-form-item>
        </el-col>
      </el-row>

    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button type="info" plain @click="onCancel()">取消</el-button>
        <el-button type="primary" @click="onSubmit()">提交</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
/**
 * 管理员编辑组件
 */
import { ref } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import EsAjax from '@/utils/EsAjax';
import ApiUrls from '@/apis/index';
import { RegRule } from '@/utils/EsValidate';
// import AvatarUpload from '@/components/upload/AvatarUpload.vue';


import { userParams, userTypeList } from '@/apis/model/UserModel';
import { getNewObj } from '@/utils/EsCommon';




// ======================================================
//                      变量声明
// ======================================================

// emit
const emit = defineEmits(['success']);

const userTypeOption = ref(userTypeList);

// 表单数据
const formAttrs = getNewObj(userParams());
;
const formModel = ref(Object.assign({}, formAttrs));
// 弹窗信息
const dialogInfo = ref({
  visible: false,
  title: '',
  width: '600px',
})
// 表单组件的引用实例
const formRef = ref(null);
// 状态选项数据
const optionsOfStatus = ref({});
// 性别选项数据
const optionsOfGender = ref({});
// 角色选项数据
const optionsOfRoles = ref([]);
// 表单校验规则
const formRules = ref({
  UserName: [{ required: true, trigger: "blur", message: "请输入用户名" },],
  Email: [
    { required: true, trigger: "blur", message: "请输入邮箱" },
    { type: 'email', message: '不是有效的Email格式', trigger: 'blur' }
  ],
  Mobile: [
    { required: true, message: "请输入手机号", trigger: "change" },
    { pattern: RegRule.mobile, message: '不是有效的手机号码', trigger: 'blur' }
  ],
  RealName: [{ required: true, message: "请输入姓名", trigger: "change" }],
  IsSuper: [{ required: true, message: "请选择是否超级管理员", trigger: "change" },],
  Status: [{ required: true, message: "请选择状态", trigger: "change" }],

})

// ======================================================
//                      点击操作
// ======================================================

// 点击提交按钮
const onSubmit = () => {
  console.log('[编辑表单] onSubmit form =', formModel.value);
  formRef.value.validate((valid, fields) => {
    if (!valid) {
      console.log('表单校验失败：', fields);
      return;
    }
    let url = formModel.value.id > 0 ? ApiUrls.authAdminUpdate : ApiUrls.authAdminSave;
    EsAjax.post(url, formModel.value).then(res => {
      if (res.data.code !== 200) {
        ElMessage.warning(res.data.msg);
        return;
      }
      dialogInfo.value.visible = false;
      emit('success');
    }).catch(err => {
      ElMessage.error('网络错误：' + err.message);
    })
  })
}

// 点击重置表单按钮
const onReset = () => {
  ElMessageBox.confirm('确定要重置表单数据吗？').then(() => {
    formRef.value.resetFields();
  }).catch(() => { })
}

// 点击取消按钮
const onCancel = () => {
  formRef.value.resetFields();
  dialogInfo.value.visible = false;
}

// ======================================================
//                      处理事件
// ======================================================

// 加载数据
const show = (id, title, item, width = '600px') => {
  dialogInfo.value.title = title;
  dialogInfo.value.width = width;
  dialogInfo.value.visible = true;
  // 加载详情数据
  if (id) {
    formModel.value = Object.assign({ ...formAttrs }, getNewObj(item));
  }
  // 加载角色选项数据
  EsAjax.post(ApiUrls.roleDatagrid).then(res => {
    console.log('加载角色选项数据', res);
    if (res.data.code !== 200) {
      ElMessage.warning(res.data.msg);
      return;
    }
    optionsOfRoles.value = res.data.data.data;
  }).catch(err => { ElMessage.error('网络错误：' + err.message) })




}

defineExpose({
  show
})
</script>

<style scoped>
</style>
